package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.rediskey.RedisKeys;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;

import static cn.wolfcode.wolf2w.domain.UserInfo.STATE_NORMAL;

@Service
//@Transactional
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        userInfoRepository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoRepository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo userInfo = userInfoRepository.findByPhone(phone);
        // 如果 userInfo 不为空,则为 true,表示手机号码存在,否则为 false
        return userInfo!=null;
    }

    @Override
    public void sendVerifyCode(String phone) {
        // 获取手机号码,创建一个验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        // 给用户提示验证码的有效时间
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder builder = stringBuilder.append("【叩丁狼】").append("你的验证码是:").append(code).append(",请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内验证");
        System.out.println(builder);

       /* RestTemplate restTemplate = new RestTemplate();
        String url = "https://way.jd.com/kaixintong/kaixintong?&mobile={1}&content={2}&appkey={3}";
        String appkey = "8096191d62652be809d8a181bab05e96";
        // 参数1:url, 参数2:返回 String 类型, 参数3:手机号码, 参数4:响应的信息, 参数5:密钥
        String result = restTemplate.getForObject(url, String.class, phone, builder.toString(), appkey);
        System.out.println(result);
        if (!result.contains("Susccess")){
            throw new LogicException("验证码发送失败");
        }*/

        // 将 phone = code 存入 redis
        userInfoRedisService.saveVerifyCode(phone,code);
        // 存入一个常量,用于控制短信发送频率
    }

    @Override
    public boolean checkverifyCode(String phone, String verifyCode) {
        // 获取当前的验证码与 redis 中的验证码对比是否一样
        //String key = "Verify_Code"+phone;
        return verifyCode.equals(userInfoRedisService.getVerifyCode(RedisKeys.VERIFY_CODE.getRedisKey(phone)));

    }

    @Override
    public void regist(String nickname, String rpassword,String password, String phone, String verifyCode) {
        // 参数判空
        AssertUtil.hasLength(nickname,"昵称不能为空!");
        AssertUtil.hasLength(password,"密码不能为空!");
        AssertUtil.hasLength(phone,"手机号不能为空!");
        AssertUtil.hasLength(rpassword,"确认密码不能为空!");
        AssertUtil.isEquals(password,rpassword,"密码不一致!");
        AssertUtil.hasLength(verifyCode,"验证码不能为空!");
        System.out.println(RedisKeys.VERIFY_CODE.getRedisKey(phone));
        AssertUtil.isEquals(verifyCode,userInfoRedisService.getVerifyCode(RedisKeys.VERIFY_CODE.getRedisKey(phone)),"验证码错误或已失效!");
        if (checkPhone(phone)){
            throw new LogicException("该手机号码已被注册!");
        }
        UserInfo userInfo = new UserInfo();
        // 以下操作设置为"",让层次对齐,好看一点
        userInfo.setEmail("");
        userInfo.setCity("");
        userInfo.setPhone(phone);
        // 密码加密
        String md5Password = Md5Utils.getMD5(password);
        System.out.println("密码:"+md5Password);
        userInfo.setPassword(md5Password);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setNickname(nickname);
        userInfo.setState(STATE_NORMAL);
        //throw new IllegalArgumentException("11111111111111111111111111");
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        AssertUtil.hasLength(username,"用户名不能为空!");
        AssertUtil.hasLength(password,"密码不能为空!");
        // 密码加密
        String md5Password = Md5Utils.getMD5(password);
        //System.out.println(md5Password);
        // 判断用户是否存在,不存在则提示
        UserInfo user = userInfoRepository.findByPhone(username);
        //user.setPassword(md5Password);
        if (user == null || !md5Password.equals(user.getPassword())){
            throw new LogicException("用户名或密码错误");
        }else {
            // 存在则返回 user
            return user;
        }
    }


}
